package com.kyrioscraft.cloud.common.util;

import com.google.common.collect.Lists;
import com.kyrioscraft.cloud.common.vo.TreeNode;

import java.util.List;

/**
 * @Author kyrioscraft
 * @Date 2018/12/17 10:03
 * @Description //TODO
 **/
public class TreeUtil {
    /**
     * 两层循环实现建树
     *
     * @param treeNodes 传入的树节点列表
     */
    public static <T extends TreeNode> List<T> build(List<T> treeNodes, Object root) {
        List<T> trees = Lists.newArrayList();

        for(T t :treeNodes){
            if( root.equals(t.getParentId())){
                trees.add(t);
            }
            for (T it : treeNodes) {
                if(it.getParentId() == t.getId()) {
                    if(t.getChildren() == null ){
                        t.setChildren(Lists.newArrayList());
                    }
                    t.addChildNode(it);
                }
            }
        }

        return trees;
    }

    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @return
     */
    public static <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, Object root) {
        List<T> trees = Lists.newArrayList();
        for(T t: treeNodes) {
            if(root.equals(t.getParentId())) {
                trees.add(findChildren(t,treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public static <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes) {
        for( T it : treeNodes) {
            if(treeNode.getId() == it.getParentId()) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(Lists.newArrayList());
                }
                treeNode.addChildNode(findChildren(it,treeNodes));
            }
        }
        return treeNode;
    }
}
